package com.mall.book.utils;

import io.jsonwebtoken.*;

import java.util.Date;

/**
 * Created by Dizziness on 2022/3/31 20:54
 */
public class JwtUtil {
    private static final String SECRET = "secret_key_code";  //生成token的前缀

    //生成Token
    public static String genToken(String userAccount) {
        String compact = Jwts.builder()
                .setHeaderParam("alg", "SHA256")
                .setHeaderParam("typ", "JWT")
                .setSubject(userAccount)
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
        return compact;
    }

    //校验Token
    public static String verifyToken(String token) {
        String subject = "";
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
            subject = claimsJws.getBody().getSubject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //部分业务可能依赖载荷信息，所以此处做返回，与正常校验流程无关
        return subject;
    }
}